package com.park.web.util.pdf;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.park.common.empty.EmptyUtils;
import com.park.web.util.close.CloseUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class PdfUtil {

	private static final  Logger logger = LoggerFactory.getLogger(PdfUtil.class);
	
	private PdfUtil(){}
	
	/**
	 * 文本转pdf
	 */
	public static void textToPdf(String textPath,String pdfPath) {
		BufferedReader read = null;
		Document document = null;
		FileOutputStream out = null;
		try {
			BaseFont bfChinese = BaseFont.createFont("/fonts/STKAITI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
			out = new FileOutputStream(URLDecoder.decode(pdfPath,"UTF-8"));
			document = new Document(PageSize.A4, 50, 50, 50, 50);
			PdfWriter.getInstance(document, out);
			document.open();
			//设置书名
			 PdfPTable table1 = new PdfPTable(1);
//			PdfPCell cell = new PdfPCell(new Paragraph("",new Font(bfChinese, 24, com.itextpdf.text.Font.BOLD)));
//			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
//			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
//			cell.setBorder(0);
            //设置每列宽度比例   
            int width[] = {100};
            table1.setWidths(width); 
            table1.getDefaultCell().setBorder(0);
//            table1.addCell(cell);
            document.add(table1);
            //加入空行
//            Paragraph blankRow = new Paragraph(18f, " ", fontChinese); 
//            document.add(blankRow);
			//创建章节下的子章节
			Paragraph paragraph = new Paragraph();
			paragraph.setFont(fontChinese);
			read = new BufferedReader(new FileReader(textPath));
			String line = read.readLine();
			while(line != null){
				paragraph.add(line+"\n");
				line = read.readLine();
			}
			document.add(paragraph);
		} catch (Exception e) {
			logger.error("text转换成pdf错误",e);
		}finally{
			CloseUtil.close(read);
			if(document != null){
				document.close();
			}
			CloseUtil.close(out);
		}
	}
	
	/** 
     * 图片转PDF 
     */  
    public static File picToPdf(String sourceFile, String destFile) {  
        File inputFile = new File(sourceFile);  
        if (!inputFile.exists()) {
            return null;// 找不到源文件, 则返回null  
        }  
        // 如果目标路径不存在, 则新建该路径  
        File outputFile = new File(destFile);  
        if (!outputFile.getParentFile().exists()) {  
            outputFile.getParentFile().mkdirs();  
        }  
        return imgToPdf(sourceFile, destFile);  
    }  
	
	/**
	 * 各种图片为pdf 
	 */
    private static File imgToPdf(String sourceFile,String destFile) {   
	        if(EmptyUtils.isEmpty(sourceFile)){  
	            return null;  
	        }  
	        Document document = new Document(PageSize.A4, 20, 20, 20, 20);
	        File outPdfFile = null;
	        try {
	            PdfWriter.getInstance(document, new FileOutputStream(destFile));    
	            document.open();    
	            document.newPage();    
	            Image png = Image.getInstance(sourceFile);    
	            float width = png.getWidth();    
	            int percent = getPercent2(width);    
	            png.setAlignment(Image.MIDDLE);    
	           png.scalePercent(percent+3);// 表示是原来图像的比例
	           document.add(png);    
	           document.close();
	           outPdfFile = new File(destFile);    
		       if (!outPdfFile.exists()) {  
		        	outPdfFile.delete(); 
		            return null;
		        }
		        outPdfFile.createNewFile();
	        } catch (Exception e) {    
	            e.printStackTrace();    
	        }    
	        return outPdfFile;    
	    }   
	 
	  /**  
	     * 第二种解决方案，统一按照宽度压缩 这样来的效果是，所有图片的宽度是相等的，自我认为给客户的效果是最好的  
	     */    
	 private static int getPercent2( float w) {    
	        int p = 0;    
	        float p2 = 530 / w * 100;    
	        p = Math.round(p2);    
	        return p;    
	    }  
	    
	    /**  
	     * 第一种解决方案 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩  
	     */    
	    @SuppressWarnings("unused")
		private static int getPercent(float h, float w) {    
	        int p = 0;    
	        float p2;    
	        if (h > w) {    
	            p2 = 297 / h * 100;    
	        } else {    
	            p2 = 210 / w * 100;    
	        }    
	        p = Math.round(p2);    
	        return p;    
	    }    
	    
	    @SuppressWarnings("restriction")
		public static void createScreenShoot(String sourceFile, String targetFile) {
		    File file = new File(sourceFile);
		    if (!file.exists()) {
		      return;
		    }
		    RandomAccessFile raf  = null;
		    try{
		      raf = new RandomAccessFile(file, "r");
		      FileChannel channel = raf.getChannel();
		      ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
		      PDFFile pdffile = new PDFFile(buf);
		      PDFPage page = pdffile.getPage(1);
		      Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
		      java.awt.Image img = page.getImage(rect.width, rect.height, // width &
		              rect, // clip rect
		              null, // null for the ImageObserver
		              true, // fill background with white
		              true // block until drawing is done
		              );
		       BufferedImage tag = new BufferedImage(rect.width, rect.height,   BufferedImage.TYPE_INT_RGB);
		       tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,null);
		       FileOutputStream out = new FileOutputStream(targetFile);
		       JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		      encoder.encode(tag); // JPEG编码
		      out.close();
		   }catch(Exception e){
		     logger.error("pdf转图片出错",e);
		   }finally {
			   CloseUtil.close(raf);
		}
	}
	
}
